package com.future.mayi.qsale.widget;

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewStub;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.baselib.utils.ToastUtils;
import com.future.mayi.R;
import com.future.mayi.model.interfaces.OnItemClickListener;
import com.future.mayi.qsale.dialog.SalePhotoSampleDialog;
import com.future.mayi.qsale.model.QsaleCateModel;
import com.future.mayi.qsale.model.QsaleGoodsListModel;
import com.future.mayi.qsale.response.CateListResponse;
import com.future.mayi.qsale.view.SelectImgView;
import com.future.mayi.utils.Arith;
import com.future.mayi.utils.HCUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/8/20.
 */

public class ConsignSaleItemLayout extends RelativeLayout {

    @BindView(R.id.iv_delete)
    ImageView ivDelete;
    @BindView(R.id.select_image_view)
    SelectImgView selectImageView;
    @BindView(R.id.tv_hint)
    TextView tvHint;
    @BindView(R.id.tv_photo_sample)
    TextView tvPhotoSample;
    @BindView(R.id.iv_brand_arrow)
    ImageView ivBrandArrow;
    @BindView(R.id.tv_brand)
    TextView tvBrand;
    @BindView(R.id.rl_brand)
    RelativeLayout rlBrand;
    @BindView(R.id.iv_style_arrow)
    ImageView ivStyleArrow;
    @BindView(R.id.tv_style)
    TextView tvStyle;
    @BindView(R.id.rl_style)
    RelativeLayout rlStyle;
    @BindView(R.id.tv_hint_price)
    TextView tvHintPrice;
    @BindView(R.id.edt_price)
    EditText edtPrice;
    @BindView(R.id.rl_price)
    RelativeLayout rlPrice;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.edt_size)
    EditText edtSize;
    @BindView(R.id.rl_size)
    RelativeLayout rlSize;
    @BindView(R.id.rl_desc)
    RelativeLayout rlDesc;
    @BindView(R.id.edt_desc)
    EditText edtDesc;
    @BindView(R.id.tv_text_num)
    TextView tvTextNum;
    @BindView(R.id.stub_have_edited)
    ViewStub stubHaveEdited;
    @BindView(R.id.ll_edit_container)
    LinearLayout llEditContainer;


    private Context mContext;

    public ConsignSaleItemLayout(Context context) {
        this(context, null);
    }

    public ConsignSaleItemLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ConsignSaleItemLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.mContext = context;
        initView();
        initListener();
    }

    private void initView() {
        LayoutInflater.from(mContext).inflate(R.layout.layout_consign_item, this);
        ButterKnife.bind(this);

        selectImageView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void OnItem(View view, int position) {
                if (mOnQsaleItemListener != null) {
                    mOnQsaleItemListener.onSelectImgClick(position, selectImageView.getMaxSelectNum());
                }
            }

            @Override
            public void OnLongItem(View view, int position) {

            }
        });
    }

    private void initListener() {

        edtDesc.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                tvTextNum.setText(edtDesc.getText().toString().length() + "/200");
            }
        });
    }


    @OnClick({R.id.iv_delete, R.id.tv_photo_sample, R.id.rl_brand, R.id.rl_style})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_delete:
                if (mOnQsaleItemListener != null) {
                    mOnQsaleItemListener.onDeleteClick();
                }
                break;
            case R.id.tv_photo_sample:
                SalePhotoSampleDialog salePhotoSampleDialog = new SalePhotoSampleDialog(mContext);
                salePhotoSampleDialog.show();
                break;
            case R.id.rl_brand:
                getRecycleBrand();
                break;
            case R.id.rl_style:
                getRecycleStyle();
                break;
        }
    }

    /**
     * 编辑状态
     */
    public void editStatus() {
        if (stubHaveEdited != null) {
            stubHaveEdited.setVisibility(GONE);
        }
        llEditContainer.setVisibility(VISIBLE);
    }

    //已经完成状态的View

    private ImageView ivImage;
    private TextView tvTitle;
    private TextView tvPrice;
    private ImageView ivEdit;

    /**
     * 保存输入,转换成已完成状态
     */
    public boolean completedStatus() {
        if (verifyInput()) {
            llEditContainer.setVisibility(GONE);
            if (stubHaveEdited.getParent() != null) {
                stubHaveEdited.inflate();
                ivImage = (ImageView) findViewById(R.id.iv_image);
                tvTitle = (TextView) findViewById(R.id.tv_title);
                ivEdit = (ImageView) findViewById(R.id.iv_edit);
                tvPrice = (TextView) findViewById(R.id.tv_price);
            } else {
                stubHaveEdited.setVisibility(VISIBLE);
            }
            saveCompletedView();
            return true;
        } else {
            return false;
        }
    }

    /**
     * 保存完成状态的数据
     */
    private void saveCompletedView() {
        Glide.with(mContext).load(selectImageView.getImg().get(0)).placeholder(R.color.black4).into(ivImage);
        tvPrice.setText(Arith.getFormatPrice(Float.parseFloat(edtPrice.getText().toString())));
        tvTitle.setText(tvBrand.getText().toString() + "-" + tvStyle.getText().toString());
        ivEdit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnQsaleItemListener != null) {
                    mOnQsaleItemListener.showEditDetail((Long) ConsignSaleItemLayout.this.getTag(R.id.item_layout_tag));
                }
            }
        });
    }

    public boolean verifyInput() {
        if (selectImageView.getImg() == null || selectImageView.getImg().size() == 0) {
            toast("请选择图片");
            return false;
        }
        if (tvBrand.getTag(R.id.cate_id) == null) {
            toast("请选择品牌");
            return false;
        }
        if (tvStyle.getTag(R.id.cate_id) == null) {
            toast("请选择款式");
            return false;
        }
        if (TextUtils.isEmpty(edtPrice.getText().toString())) {
            toast("请输入期望价格");
            return false;
        }
        return true;
    }

    /**
     * 获取上传的图片本地地址
     *
     * @return
     */
    public List<String> getImgPath() {
        return selectImageView.getImg();
    }

    /**
     * 获取上传数据模型
     *
     * @return
     */
    public QsaleGoodsListModel getUploadModel() {
        QsaleGoodsListModel qsaleGoodsListModel = new QsaleGoodsListModel();
        qsaleGoodsListModel.setBrand_name(tvBrand.getText().toString());
        qsaleGoodsListModel.setStyle_name(tvStyle.getText().toString());
        qsaleGoodsListModel.setStyle_id((Integer) tvStyle.getTag(R.id.cate_id));
        qsaleGoodsListModel.setSize(edtSize.getText().toString());
        qsaleGoodsListModel.setDescribe(edtDesc.getText().toString());
        qsaleGoodsListModel.setExpect_price(Float.parseFloat(edtPrice.getText().toString()));
        return qsaleGoodsListModel;
    }

    private void getRecycleBrand() {
        showLoadingDialog();
        new HttpRequest<CateListResponse>()
                .with(mContext)
                .setApiCode(ApiCst.getBrandOrStyle)
                .addParam("type", 20)
                .setListener(new HttpRequest.OnNetworkListener<CateListResponse>() {
                    @Override
                    public void onSuccess(CateListResponse response) {
                        dismissLoadingDialog();
                        showSelectBrandPickerView(response.getQSaleCateList());
                    }

                    @Override
                    public void onFail(String message, CateListResponse response) {
                        dismissLoadingDialog();
                        HCUtils.loadFail(mContext, message);
                    }
                }).start(new CateListResponse());
    }

    private void showSelectBrandPickerView(final List<QsaleCateModel> qsaleCateModels) {
        if (qsaleCateModels == null || qsaleCateModels.size() == 0) return;
        final List<String> brandNames = new ArrayList<>(qsaleCateModels.size());
        for (int i = 0; i < qsaleCateModels.size(); i++) {
            brandNames.add(qsaleCateModels.get(i).getCate_name());
        }
        OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvBrand.setText(brandNames.get(options1));
                tvBrand.setTag(R.id.cate_id, qsaleCateModels.get(options1).getCate_id());
                tvStyle.setText("");
                tvStyle.setTag(R.id.cate_id, null);
            }
        }).build();
        optionsPickerView.setPicker(brandNames);
        optionsPickerView.show();
    }

    private void getRecycleStyle() {
        if (tvBrand.getTag(R.id.cate_id) == null) {
            ToastUtils.shortToast(mContext, "请先选择品牌");
            return;
        }
        int cateId = (int) tvBrand.getTag(R.id.cate_id);
        showLoadingDialog();
        new HttpRequest<CateListResponse>()
                .with(mContext)
                .setApiCode(ApiCst.getBrandOrStyle)
                .addParam("pid", cateId)
                .addParam("type", 20)
                .setListener(new HttpRequest.OnNetworkListener<CateListResponse>() {
                    @Override
                    public void onSuccess(CateListResponse response) {
                        dismissLoadingDialog();
                        showSelectStylePickerView(response.getQSaleCateList());

                    }

                    @Override
                    public void onFail(String message, CateListResponse response) {
                        dismissLoadingDialog();
                        HCUtils.loadFail(mContext, message);
                    }
                }).start(new CateListResponse());

    }

    private void showSelectStylePickerView(final List<QsaleCateModel> qsaleCateModels) {
        if (qsaleCateModels == null || qsaleCateModels.size() == 0) return;
        final List<String> styleNames = new ArrayList<>(qsaleCateModels.size());
        for (int i = 0; i < qsaleCateModels.size(); i++) {
            styleNames.add(qsaleCateModels.get(i).getCate_name());
        }
        OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvStyle.setText(styleNames.get(options1));
                tvStyle.setTag(R.id.cate_id, qsaleCateModels.get(options1).getCate_id());
            }
        }).build();
        optionsPickerView.setPicker(styleNames);
        optionsPickerView.show();
    }


    /**
     * 成功添加图片
     *
     * @param pathList
     */
    public void addImg(List<String> pathList) {
        if (selectImageView != null) {
            selectImageView.addImg(pathList);
        }
    }

    /**
     * 是否正在编辑状态
     *
     * @return
     */
    public boolean isEditedStatus() {
        return llEditContainer.getVisibility() == VISIBLE;
    }

    private void toast(String message) {
        ToastUtils.shortToast(mContext, message);
    }

    private void showLoadingDialog() {
        if (mOnQsaleItemListener != null) {
            mOnQsaleItemListener.showWaitingDialog();
        }
    }

    private void dismissLoadingDialog() {
        if (mOnQsaleItemListener != null) {
            mOnQsaleItemListener.dismissWaitingDialog();
        }
    }

    private OnQSaleItemListener mOnQsaleItemListener;

    public void setOnQsaleItemListener(OnQSaleItemListener onQsaleItemListener) {
        this.mOnQsaleItemListener = onQsaleItemListener;
    }

    public interface OnQSaleItemListener {

        void onSelectImgClick(int position, int maxItem);

        void onDeleteClick();

        void showWaitingDialog();

        void dismissWaitingDialog();

        void showEditDetail(long layoutCreateTag);
    }
}
